package com.tanhua.dubbo.api.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.service.IdService;
import com.tanhua.dubbo.api.service.TimeLineService;
import com.tanhua.dubbo.enums.CommentType;
import com.tanhua.dubbo.enums.IdType;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@DubboService(version = "1.0.0")
public class QuanZiApiImpl implements QuanZiApi {

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    private String getCommentRedisKey(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKey(Long userId) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX + userId;
    }

    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageRequest);

        //查询自己的时间线
        List<TimeLine> timeLines = this.mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        //获取自己时间线内 发布的动态的id
        List<Object> publishIdList = CollUtil.getFieldValues(timeLines, "publishId");

        Query publishQuery = Query.query(Criteria.where("id").in(publishIdList))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(publishQuery, Publish.class);

        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(publishList);

        return pageInfo;

    }

    @Override
    public String savePublish(Publish publish) {
        if(!ObjectUtil.isAllNotEmpty(publish.getText(), publish.getUserId(), publish.getMedias())) {
            return null;
        }

        publish.setId(ObjectId.get());
        publish.setPid(this.idService.createId(IdType.PUBLISH));
        publish.setCreated(System.currentTimeMillis());
        publish.setSeeType(1);

        this.mongoTemplate.save(publish);

        Album album = new Album();
        album.setId(ObjectId.get());
        album.setPublishId(publish.getId());
        album.setCreated(System.currentTimeMillis());
        this.mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

        //写入好友的时间线表
        this.timeLineService.saveTimeLine(publish.getUserId(), publish.getId());

        return publish.getId().toHexString();
    }

    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //获取推荐的动态的id集合
        String redisKey = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String publishs = this.redisTemplate.opsForValue().get(redisKey);
        String[] publishIdArr = publishs.split(",");
        List<Long> publishIdList = new ArrayList<>();
        for (String publishId : publishIdArr) {
            publishIdList.add(Convert.toLong(publishId));
        }

        //对推荐动态ID集合进行分页查询
        int start = PageUtil.getStart(page - 1, pageSize);
        int end = PageUtil.getEnd(page - 1, pageSize);
        end = Math.min(publishIdList.size(), end);

        //分页查询,获取实际要查询的动态id
        List<Long> pidList = new ArrayList<>();
        for(int i = start; i < end; i++) {
            Long publishId = publishIdList.get(i);
            pidList.add(publishId);
        }

        //开始查询
        Query query = Query.query(Criteria.where("pid").in(pidList));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);

        //按照推荐的顺序进行加入
        pageInfo.setRecords(new ArrayList<>());
        for (Long pid : pidList) {
            for (Publish publish : publishList) {
                if(ObjectUtil.equal(publish.getPid(), pid)) {
                    pageInfo.getRecords().add(publish);
                    break;
                }

            }
        }

        return pageInfo;
    }

    //-------------------点赞
    @Override
    public Publish queryPublishById(String id) {
        Query query = Query.query(Criteria.where("id").is(new ObjectId(id)));
        return this.mongoTemplate.findOne(query, Publish.class);
    }

    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //判断是动态id还是评论id
        Video video = this.queryVideoById(publishId);
        Publish publish = this.queryPublishById(publishId);
        Comment commentById = this.queryCommentById(publishId);
        if(ObjectUtil.isNotEmpty(publish)) {

            return commonLikeMethod(userId, publishId, publish.getUserId());

        } else if(ObjectUtil.isNotEmpty(commentById)) {

            return commonLikeMethod(userId, publishId, commentById.getUserId());

        } else if(ObjectUtil.isNotEmpty(video)) {

            return commonLikeMethod(userId, publishId, video.getUserId());

        }
        return false;
    }

    //公共点赞方法
    private Boolean commonLikeMethod(Long userId, String publishId, Long userId2) {
        //判断该用户是否已经点赞
        if (this.queryUserIsLike(userId, publishId)) {
            return false;
        }

        //将数据保存到MongoDB
        Comment comment = new Comment();
        comment.setCommentType(CommentType.Like.getType());
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(publishId));
        comment.setIsParent(false);
        comment.setUserId(userId);
        //Publish publish = this.queryPublishById(publishId);
        comment.setPublishUserId(userId2);
        this.mongoTemplate.save(comment);

        //将点赞数以及用户是否点赞记录到redis中
        String redisKey = this.getCommentRedisKey(publishId);
        Object hashKey = CommentType.Like.name();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        //标识该用户已经点赞
        this.redisTemplate.opsForHash().put(redisKey, this.getCommentUserLikeRedisKey(userId), "1");

        return true;
    }

    @Override
    public Video queryVideoById(String videoId) {
        Query query = Query.query(Criteria.where("id").is(new ObjectId(videoId)));
        return this.mongoTemplate.findOne(query, Video.class);
    }

    @Override
    public Comment queryCommentById(String commentId) {
        Query query = Query.query(Criteria.where("_id").is(new ObjectId(commentId))
                .and("commentType").is(CommentType.COMMENT.getType()));
        Comment comment = this.mongoTemplate.findOne(query, Comment.class);
        return comment;
    }

    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        if(!this.queryUserIsLike(userId, publishId)) {
            return false;
        }

        //删除mongodb中的记录
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.Like.getType()));
        this.mongoTemplate.remove(query, Comment.class);

        //修改redis中的数据
        String redisKey = getCommentRedisKey(publishId);
        Object hashKey = CommentType.Like.name();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        //删除已点赞的标志
        this.redisTemplate.opsForHash().delete(redisKey, this.getCommentUserLikeRedisKey(userId));
        return true;
    }

    @Override
    public Long queryLikeCount(String publishId) {
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.Like.name();
        return Convert.toLong(this.redisTemplate.opsForHash().get(redisKey, hashKey), 0L);
    }

    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        //判断否为评论
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = this.getCommentUserLikeRedisKey(userId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);

    }

    //-------------------喜欢
    @Override
    public Boolean loveComment(Long userId, String publishId) {
        //判断是否已经喜欢
        Boolean isLove = this.queryUserIsLove(userId, publishId);
        if(isLove) {
            return false;
        }

        //创建mongdb存储对象comment
        Comment comment = new Comment();
        comment.setCommentType(CommentType.LOVE.getType());
        //comment.setId(new ObjectId());
        comment.setCreated(System.currentTimeMillis());
        comment.setIsParent(false);
        comment.setUserId(userId);
        Publish publish = this.queryPublishById(publishId);
        comment.setPublishUserId(publish.getUserId());
        comment.setPublishId(new ObjectId(publishId));
        this.mongoTemplate.save(comment);

        //在redis中对喜欢数+1
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey_love = CommentType.LOVE.name();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey_love, 1);

        //在redis中加入喜欢标记
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        return true;
    }

    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        //判断动态状态是否为喜欢
        Boolean isLove = this.queryUserIsLove(userId, publishId);
        if(!isLove) {
            return false;
        }

        //删除mongodb中的喜欢记录
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.LOVE.getType()));
        this.mongoTemplate.remove(query, Comment.class);

        //redis中喜欢数-1
        String redisKey = this.getCommentRedisKey(publishId);
        Object hashKey = CommentType.LOVE.name();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        //redis中将喜欢标记置为0
        String hashKey_love = this.getCommentUserLoveRedisKey(userId);
        this.redisTemplate.opsForHash().delete(redisKey, hashKey_love);

        return true;
    }

    @Override
    public Long queryLoveCount(String publishId) {
        //从redis中获取喜欢数
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = CommentType.LOVE.name();
        Long count = Convert.toLong(this.redisTemplate.opsForHash().get(redisKey, hashKey));
        return count;
    }

    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        //从redis中查看是否喜欢
        String redisKey = this.getCommentRedisKey(publishId);
        String hashKey = this.getCommentUserLoveRedisKey(userId);
        Boolean isLove = ObjectUtil.equal(this.redisTemplate.opsForHash().get(redisKey, hashKey), "1");
        return isLove;
    }

    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType()))
                .with(pageRequest);
        List<Comment> comments = this.mongoTemplate.find(query, Comment.class);

        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setTotal(comments.size());
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(comments);

        return pageInfo;
    }

    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        Publish publish = this.queryPublishById(publishId);
        Video video = this.queryVideoById(publishId);
        if(ObjectUtil.isNotEmpty(publish)) {
            Comment comment = new Comment();
            comment.setCommentType(CommentType.COMMENT.getType());
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());
            //comment.setId(ObjectId.get());

            comment.setPublishUserId(publish.getUserId());
            comment.setUserId(userId);
            comment.setIsParent(false);
            comment.setPublishId(new ObjectId(publishId));

            try {
                this.mongoTemplate.save(comment);
//            Publish publish1 = BeanUtil.toBeanIgnoreError(comment, Publish.class);
//            mongoTemplate.save(publish1);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        } else if(ObjectUtil.isNotEmpty(video)) {
            Comment comment = new Comment();
            comment.setCommentType(CommentType.COMMENT.getType());
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());
            //comment.setId(ObjectId.get());

            comment.setPublishUserId(video.getUserId());
            comment.setUserId(userId);
            comment.setIsParent(false);
            comment.setPublishId(new ObjectId(publishId));

            try {
                this.mongoTemplate.save(comment);
//            Publish publish1 = BeanUtil.toBeanIgnoreError(comment, Publish.class);
//            mongoTemplate.save(publish1);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
        return false;
    }

    @Override
    public Integer queryCommentCount(ObjectId publishId) {
        Query query = Query.query(Criteria.where("publishId").is(publishId)
                .and("commentType").is(CommentType.COMMENT.getType()));
        List<Comment> comments = this.mongoTemplate.find(query, Comment.class);

        return comments.size();
    }

    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //查询我的相册表 -> 发布id列表
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        List<Album> albumList = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);

        //根据发布id查询发布对象
        List<Object> publishIdList = CollUtil.getFieldValues(albumList, "publishId");
        Query publishQuery = Query.query(Criteria.where("id").in(publishIdList))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(publishQuery, Publish.class);

        pageInfo.setRecords(publishList);

        return pageInfo;
    }
}
